
package com.ai.networking.netty.service;

import com.ai.networking.netty.decoder.L1ToSysMessageDecoder;
import com.ai.networking.netty.handler.HearBeatHandler;
import com.ai.networking.netty.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.nio.charset.Charset;

/**
 * 监听 Socket 服务
 *
 * @author chen
 */
@Slf4j
public class NettyServer implements Runnable {

    int[] ports;

    /**
     * 通过构造方法将端口信息注入
     * 单个服务端可以监听多个端口
     * @param ports
     */
    public NettyServer(int[] ports) {
        this.ports = ports;
    }

    /**
     * Socket监听
     */

    public void SocketListener(int... ports) {
        //
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("================5.NettyServer开始启动========================");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            log.info("================7.1 NettyServer 端口为：" + ports + "========================");
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)  //绑定线程池
                    .channel(NioServerSocketChannel.class)  // 指定使用的channel
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 65535, 65535))
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            InetAddress ip = ch.remoteAddress().getAddress();//获取客户端的ip信息

                            int port = ch.remoteAddress().getPort();//客户端的端口

                            String address = ip.getHostAddress();

                            ch.pipeline().addLast(new L1ToSysMessageDecoder());

                            log.info("================7.2 报告，有个socket客户端链接到本服务器, IP为：" + address + ", Port为：" + port + "========================");

                            ch.pipeline().addLast(new IdleStateHandler(0, //没有收到客户端发送的数据，就会抛出读超时异常事件
                                    0, //0s服务端没有给客户端发送数据，就会抛出写超时异常事件
                                    30)); //30s内读写事件都没有发生，就会抛出全超时异常事件
                            ch.pipeline().addLast(new HearBeatHandler());//处理超时事件

                            ch.pipeline().addLast(new ServerHandler(address,port))// 客户端触发操作----处理客户端
                                    .addLast(new StringEncoder(Charset.forName("UTF-8")));
//                                    .addLast(new StringDecoder(Charset.forName("UTF-8")));
                        }
                    });

            log.info("================8.NettyServer 启动中.....========================");
            ChannelFuture[] channelFutures;
            ChannelFuture futureTcp;
            if (ports.length > 0) {
                channelFutures = new ChannelFuture[ports.length];
                int i = 0;
                for (Integer port : ports) {
                    // 绑定端口，同步等待成功 绑定的服务器
                    futureTcp = bootstrap.bind(port).sync();
                    channelFutures[i++] = futureTcp;
                    futureTcp.addListener(future -> {
                        if (future.isSuccess()) {
                            System.out.println("netty server 启动成功!" + port);
                        } else {
                            System.out.println("netty server 启动失败!" + port);
                        }
                    });
                }

//            ChannelFuture channelFuture = bootstrap.bind(CommonService.PORT).sync(); // 服务器异步创建绑定

                log.info("================9.NettyServer 启动完毕！！========================");
                for (ChannelFuture future : channelFutures) {
                    /**
                     * 等待服务器监听端口关闭
                     * 手动阻塞所有的信道，当信道关闭之后，自动释放线程
                     */
                    future.channel().closeFuture().sync();
                }
//            channelFuture.channel().closeFuture().sync(); // 关闭服务器通道
                log.info("================41.NettyServer 关闭服务器通道！！========================");
            }


        } catch (Exception e) {
            log.error("================4.1 NettyServer  启动出现异常， 异常内容为：" + e.getMessage() + "========================");
        } finally {
            log.error("================4.2 NettyServer 服务关闭========================");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * @see Runnable#run()
     */
    @Override
    public void run() {
        log.info("================4.多线程启动Netty Server========================");
        this.SocketListener(ports);
    }
}
